class AuthUserController {

    static authorize = "admin"

    def index = {redirect(action: list, params: params)}

    // the delete, save and update actions only accept POST requests
    def allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

    def list = {
        if (!params.max) params.max = 10
        log.debug "*** THE LIST ***" + AuthUser.list()
                [userList: AuthUser.list(params)]
    }

    def show = {
                [user: AuthUser.get(params.id)]
    }

    def delete = {
        def user = AuthUser.get(params.id)
        if (!user) {
            flash.message = "user.not.found.for.id"
            render(view: "show", model: [user: AuthUser.get(params.id)])
            return;
        }

        if (user.username == "admin") {
            flash.message = "user.admin.reserved"
            render(view: "show", model: [user: AuthUser.get(params.id)])
            return;
        }

        if (user.delete()) {
            flash.message = "User ${user.username} deleted."
            redirect(action: list)
        } else {
            flash.message = "User not found with id ${params.id}"
            redirect(action: list)
        }
    }

    def create = {
        def user = new AuthUser()
        user.properties = params
        return ['user': user]
    }

    def save = {
        def user = new AuthUser()
        user.properties = params
        user.passwordEnc = params.password.encodeAsPassword()
        user.hash = "${user.username}:${user.email}:${new Date()}".encodeAsPassword()
        if (user.save()) {
            flash.message = "User ${user.username} created."
            redirect(action: show, id: user.id)
        }
        else {
            render(view: 'create', model: [user: user])
        }
    }

    def addRole = {
                [user: AuthUser.get(params.id)]
    }

    def update = {
        log.debug "UPDATE***"
        log.debug params
        def user = AuthUser.get(params.id)
        AuthRole.list().each {role ->
            if (params."role_${role.id}") {
                log.debug "found role ${role.name} ${role.id} selected"
                if (!user.hasRole(role)) {
                    user.addToRoles(role)
                }
            } else {
                if (user.hasRole(role)) {
                    user.removeFromRoles(role)
                }
            }
        }
        user.save()
        redirect(action: list)
    }
}